package com.tanhua.app.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.UserHolder;
import com.tanhua.api.db.QuestionApi;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.RecommendUserApi;
import com.tanhua.db.Question;
import com.tanhua.db.UserInfo;
import com.tanhua.mongo.RecommendUser;
import com.tanhua.template.HuanXinTemplate;
import com.tanhua.vo.PageBeanVo;
import com.tanhua.vo.TodayBest;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RecommendService {

    @Reference
    private RecommendUserApi recommendUserApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    public ResponseEntity findMaxScore() {
        // 获取到当前用户的id
        Long userId = UserHolder.getUser().getId();
        //当前用户最高猿粪值的女神
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);
        //健壮性 如果没有推荐用户，应该给一个默认的用户
        if(recommendUser==null){
            recommendUser = new RecommendUser();
            recommendUser.setUserId(2L); //在这里是写死的  你可以做成随机的
            recommendUser.setScore(99.0); //这里的得分也是写死的
        }


        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());


        //组装vo
        TodayBest todayBest = new TodayBest();
        //猿粪值已有
        todayBest.setFateValue(recommendUser.getScore().longValue());
        //女神信息已有
        BeanUtils.copyProperties(userInfo,todayBest);
        todayBest.setTags(userInfo.getTags().split(","));
        return ResponseEntity.ok(todayBest);
    }

    public ResponseEntity findAllScore(Integer page, Integer pagesize) {
        // 去mongodb中根据当前登录用户查询到所有的佳人（分页）
        PageBeanVo vo = recommendUserApi.findAllScore(page, pagesize, UserHolder.getUser().getId());
        List<RecommendUser> items = (List<RecommendUser>) vo.getItems();
        if(items.size()==0){
            //给当前登录用户造假数据
            items=fromtuijianren();
        }
        // 根据佳人的id获取到所有佳人的信息
        List<TodayBest> list=new ArrayList<TodayBest>();
        for (RecommendUser recommendUser : items) {
            UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
            //封装TodayBest（recommendUser+userInfo）
            TodayBest todayBest = new TodayBest();
            todayBest.setFateValue(recommendUser.getScore().longValue());
            BeanUtils.copyProperties(userInfo,todayBest);
            todayBest.setTags(userInfo.getTags().split(","));
            list.add(todayBest);
        }

        // 封装app需要用的pageBeanVo
        vo.setItems(list); //覆盖
        vo.setPage(page);
        vo.setPagesize(pagesize);
        //返回即可
        return ResponseEntity.ok(vo);
    }


    // 登录人没有推荐人给的推荐（自己造的）
    private List<RecommendUser> fromtuijianren() {
        List<RecommendUser> list=new ArrayList<RecommendUser>();

        for(Long i=1l;i<=10;i++){
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(i);
            recommendUser.setScore(RandomUtils.nextDouble(60,99));
            list.add(recommendUser);
        }
        return list;
    }

    public ResponseEntity personalInfo(Long jrid) {

        // 查询userInfo
        UserInfo userInfo = userInfoApi.findById(jrid);
        // 查询recommend_user
        Long score=recommendUserApi.findScore(jrid,UserHolder.getUser().getId());
        //组装TodayBest  返回
        TodayBest todayBest = new TodayBest();
        BeanUtils.copyProperties(userInfo,todayBest);
        todayBest.setTags(userInfo.getTags().split(","));
        todayBest.setFateValue(score);
        return ResponseEntity.ok(todayBest);
    }

    public ResponseEntity strangerQuestions(Long userId) {
        Question question = questionApi.findQuestion(userId);
        if(question==null){
            question=new Question();
            question.setStrangerQuestion("你是高富帅么？");
        }
        return ResponseEntity.ok(question.getStrangerQuestion());
    }

    public ResponseEntity toStrangerQuestions(Long jrid, String content) {

        Long userId = UserHolder.getUser().getId();
        UserInfo userInfo = userInfoApi.findById(userId);
        Question question = questionApi.findQuestion(jrid);

        //调用环信  参数1：回复的佳人id
        Map<String, String> map = new HashMap<>();
        map.put("userId",userId.toString());
        map.put("nickname",userInfo.getNickname());
        map.put("strangerQuestion",question.getStrangerQuestion());
        map.put("reply",content);

        String map_json = JSON.toJSONString(map);

        huanXinTemplate.sendMsg(jrid.toString(),map_json);

        return ResponseEntity.ok(null);
    }
}
